import { ParameterObjectType, UnitInfo, useUnit } from '@amcax/base';
import { unitManager } from '@app-base/module';
import { floor, round } from 'lodash';

export const useNumberWithUnit = () => {
  const { lengthUnit, angleUnit } = useUnit();

  const getNumWithPrecision = (
    num: number,
    prec: number | undefined,
    minScientificNotificationCount?: number,
    scientificNotificationPrecision?: number,
  ) => {
    let val = num;
    if (prec == null) {
      val = num;
    }

    if (
      minScientificNotificationCount != null &&
      val >= 10 ** minScientificNotificationCount
    ) {
      const digit = Math.round(Math.log10(val));

      return `${floor(val / 10 ** digit, scientificNotificationPrecision)}e+${digit}`;
    }

    val = floor(num, prec) === 0 ? 0 : round(num, prec);

    return val;
  };

  const parseNumberWithUnit = (
    num: number,
    type: ParameterObjectType.Length | ParameterObjectType.Angle,
    precision: number | null = 6,
    minScientificNotificationCount?: number,
    scientificNotificationPrecision?: number,
  ) => {
    const getUnitParams = (
      type === ParameterObjectType.Length
        ? unitManager.getLengthUnitParams
        : unitManager.getAngleUnitParams
    ).bind(unitManager) as (unit?: string) => UnitInfo<string>;

    const currentUnit = getUnitParams(
      type === ParameterObjectType.Length ? lengthUnit : angleUnit,
    );

    return `${getNumWithPrecision(num, precision, minScientificNotificationCount, scientificNotificationPrecision)} ${currentUnit.name}`;
  };

  return {
    parseNumberWithUnit,
    getNumWithPrecision,
  };
};
